package com.thermal.thermal_inspection.controller;
import com.thermal.thermal_inspection.common.CommonResponse;
import com.thermal.thermal_inspection.entity.Report;
import com.thermal.thermal_inspection.entity.User;
import com.thermal.thermal_inspection.service.AccountService;
import com.thermal.thermal_inspection.service.ResultService;
import com.thermal.thermal_inspection.util.ResultUtil;
import com.thermal.thermal_inspection.vo.ResultRequestVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.thermal.thermal_inspection.entity.Result;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.util.List;
@RestController
@RequestMapping("/result")
public class ResultController {
    private static final String UPLOAD_DIR = "diagnosis/";

    @Autowired
    private ResultService resultService;
    @Autowired
    AccountService accountService;
    @Autowired
    ResultUtil resultUtil;
    @GetMapping("/{id}")
    public CommonResponse<Result> get(@PathVariable Integer id) {
        return CommonResponse.createForSuccess(resultService.getById(id));
    }

    @GetMapping("/list")
    public  CommonResponse<List<Result>> list() {
        return CommonResponse.createForSuccess(resultService.getAll());
    }

    @PostMapping("/generatePdf")
    public CommonResponse<String> generateResultPdf(@RequestBody ResultRequestVo vo) {
        System.out.println("生成报告！");
        // 1. 获取病人和医生信息
        User patient = accountService.getUserInfo(vo.getPatientId());
        User doctor = accountService.getUserInfo(vo.getDoctorId());

        if (patient == null || doctor == null) {
            return CommonResponse.createForError("病人或医生不存在");
        }

        // 2. 构造文件名
        String fileName = resultUtil.generateFileName(patient.getRealName(), doctor.getRealName());

        // 3. 构造 Result 实体（如需要保存数据库）
        Result result = new Result();
        result.setPatientId(vo.getPatientId());
        result.setDoctorId(vo.getDoctorId());
        result.setPatientName(patient.getRealName());
        result.setDoctorName(doctor.getRealName());
        result.setResultContent(vo.getResultContent());
        result.setDiagnosisType(vo.getDiagnosisType());
        result.setDiagnosisTime(new Timestamp(System.currentTimeMillis()));
        result.setFileUrl(fileName);

        // 4. 生成 PDF
        boolean pdfGenerated = resultUtil.generatePdf(vo, patient, doctor, UPLOAD_DIR+fileName);

        if (!pdfGenerated) {
            return CommonResponse.createForSuccess("PDF生成失败");
        }

        // 5. 保存到数据库
        resultService.add(result);

        return CommonResponse.createForSuccess(fileName);
    }
    @GetMapping("/download/{filename:.+}")
    public ResponseEntity<Resource> downloadPdfFile(@PathVariable String filename) {
        try {
            // 对文件名做URL编码，避免中文或特殊字符乱码
            String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString()).replaceAll("\\+", "%20");

            // 拼接文件路径
            Path filePath = Paths.get(UPLOAD_DIR).resolve(filename).normalize();

            // 资源加载
            Resource resource = new UrlResource(filePath.toUri());

            if (resource.exists() && resource.isReadable()) {
                // 返回文件流，设置Content-Disposition为attachment，触发下载
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFilename)
                        .header(HttpHeaders.CONTENT_TYPE, "application/pdf; charset=UTF-8")  // 这里用pdf类型更准确
                        .body(resource);
            } else {
                // 文件不存在或不可读，返回404
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 发生异常返回500
            return ResponseEntity.internalServerError().build();
        }
    }

    @DeleteMapping("/delete/{id}")
    public CommonResponse<Integer> delete(@PathVariable Integer id) {
        return CommonResponse.createForSuccess(resultService.delete(id));
    }

    @GetMapping("/search")
    public CommonResponse<List<Result>> searchResults(
            @RequestParam(required = false) String patientName,
            @RequestParam(required = false) String doctorName,
            @RequestParam(required = false) String diagnosisType) {
        List<Result> list = resultService.searchResults(patientName, doctorName, diagnosisType);
        return CommonResponse.createForSuccess(list);
    }
}

